package com.lifuixng.picturebackend.controller.picture;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.lifuixng.picturebackend.annotation.AuthCheck;
import com.lifuixng.picturebackend.api.imagesearch.ImageSearchApiFacade;
import com.lifuixng.picturebackend.api.imagesearch.mode.ImageSearchResult;
import com.lifuixng.picturebackend.api.imagesearch.mode.SearchPictureByPictureRequest;
import com.lifuixng.picturebackend.common.BaseResponse;
import com.lifuixng.picturebackend.common.DeleteRequest;
import com.lifuixng.picturebackend.common.ResultUtils;
import com.lifuixng.picturebackend.constant.UserConstant;
import com.lifuixng.picturebackend.exception.ErrorCode;
import com.lifuixng.picturebackend.exception.ThrowUtils;
import com.lifuixng.picturebackend.model.dto.picture.*;
import com.lifuixng.picturebackend.model.entity.Picture;
import com.lifuixng.picturebackend.model.entity.PictureTagCategory;
import com.lifuixng.picturebackend.model.entity.User;
import com.lifuixng.picturebackend.model.enums.PictureReviewStatusEnum;
import com.lifuixng.picturebackend.model.vo.picture.PictureVO;
import com.lifuixng.picturebackend.service.PictureService;
import com.lifuixng.picturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author Mr.LiFuXing
 * @Date 2024/12/19 14:55
 * @Title PictureController
 * @Package com.lifuixng.picturebackend.controller.picture
 */

@RestController
@RequestMapping("/picture")
@Slf4j
public class PictureController {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 本地缓存
     */
    private final Cache<String, String> LOCAL_CACHE = Caffeine.newBuilder()
            .initialCapacity(1024).maximumSize(10000L)
            .expireAfterWrite(5L, TimeUnit.MINUTES)
            .build();


    /**
     * 分页查询，管理员可以访问
     *
     * @param pictureQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> pictureListPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        Page<Picture> picturePage = pictureService.pictureListByPage(pictureQueryRequest);
        return ResultUtils.success(picturePage);
    }


    /**
     * 主页
     * 分页查询，主页展示 所有人都可以看
     *
     * @param pictureQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> pictureVOListPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                           HttpServletRequest request) {


        Page<PictureVO> picturePage = pictureService.pictureVOListByPage(pictureQueryRequest, request);
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页查询，主页展示 所有人都可以看
     * 缓存优化
     *
     * @param pictureQueryRequest
     * @return
     */
    @Deprecated
    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> pictureVOListPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                    HttpServletRequest request) {
        // String cacheValue = null;
        // // 构建key
        // String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        // String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        // String cacheKey = "picture:pictureVOListPageWithCache:" + hashKey;
        // // 在本地缓存中查村
        // cacheValue = LOCAL_CACHE.getIfPresent(cacheKey);
        // if (cacheValue != null) {
        //     // 将缓存的数据转为实体类，返回
        //     Page<PictureVO> pictureVOPage = JSONUtil.toBean(cacheValue, Page.class);
        //     return ResultUtils.success(pictureVOPage);
        // }
        //
        // // 本地缓存为空 在redis中查询
        // ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        // cacheValue = opsForValue.get(cacheKey);
        // if (cacheValue != null) {
        //     // 缓存命中
        //     Page<PictureVO> pictureVOPage = JSONUtil.toBean(cacheValue, Page.class);
        //     return ResultUtils.success(pictureVOPage);
        // }
        Page<PictureVO> picturePage = pictureService.pictureVOListByPage(pictureQueryRequest, request);

        // // 将查询结果 存放到本地缓存和redis中
        // LOCAL_CACHE.put(cacheKey, JSONUtil.toJsonStr(picturePage));
        // // 设置缓存过期时间 5-10分钟，防止redis雪崩
        // int cacheExpireTime = 300 + RandomUtil.randomInt(0, 300);
        // opsForValue.set(cacheKey, JSONUtil.toJsonStr(picturePage), cacheExpireTime, TimeUnit.SECONDS);
        return ResultUtils.success(picturePage);
    }

    /**
     * 文件上传
     *
     * @param multipartFile
     * @param pictureUploadRequest
     * @param request
     * @return
     */
    @PostMapping("/upload")
    @AuthCheck
    public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile,
                                                 PictureUploadRequest pictureUploadRequest,
                                                 HttpServletRequest request) {

        User user = userService.userLoginInfo(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, user);
        return ResultUtils.success(pictureVO);

    }

    @PostMapping("/upload/url")
    @AuthCheck
    public BaseResponse<PictureVO> uploadPictureByUrl(@RequestBody PictureUploadRequest pictureUploadRequest, HttpServletRequest request) {

        User loginUser = userService.userLoginInfo(request);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }


    @PostMapping("review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest, HttpServletRequest request) {

        User userLogin = userService.userLoginInfo(request);
        Long result = (long) pictureService.doPictureReview(pictureReviewRequest, userLogin);
        return ResultUtils.success(result);
    }


    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureByBatch(@RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
                                                      HttpServletRequest request
    ) {
        User loginUser = userService.userLoginInfo(request);
        int result = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 删除图片，管理员可以删除所有，普通用户只能删除自己的
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck
    public BaseResponse<Long> deletePictureById(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {

        Long i = (long) pictureService.deleteById(deleteRequest, request);
        return ResultUtils.success(i);
    }


    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
        Long i = (long) pictureService.updatePicture(pictureUpdateRequest, request);
        return ResultUtils.success(i);
    }


    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(Long id) {

        Picture picture = pictureService.getPictureById(id);
        return ResultUtils.success(picture);
    }

    /**
     * 获取图片列表 脱敏后的
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(Long id, HttpServletRequest request) {

        PictureVO pictureVO = pictureService.getPictureVOById(id, request);
        return ResultUtils.success(pictureVO);
    }


    /**
     * 编辑
     *
     * @param pictureEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Long> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {

        Long i = (long) pictureService.editPicture(pictureEditRequest, request);
        return ResultUtils.success(i);
    }


    /**
     * 获取图片标签和分类
     *
     * @return
     */
    @GetMapping("/tagAndCategory")
    public BaseResponse<PictureTagCategory> getTagAndCategory() {
        List<String> tag = Arrays.asList("搞笑", "生活", "艺术", "背景", "简历", "创意");
        List<String> category = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        PictureTagCategory pictureTagCategory = PictureTagCategory.builder()
                .tagList(tag)
                .categoryList(category)
                .build();

        return ResultUtils.success(pictureTagCategory);
    }


    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {

        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        Picture picture = pictureService.getPictureById(searchPictureByPictureRequest.getPictureId());
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        List<ImageSearchResult> searchResultList = ImageSearchApiFacade.searchImage(picture.getUrl());
        return ResultUtils.success(searchResultList);

    }

}
